package com.h.handler;

import com.h.annotation.Handler;
import com.h.autoconfigure.NettyConfigProperties;
import com.h.config.ChannelFactory;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ：Hukaiwen
 * @description：
 * @date ：2022/2/22 15:32
 */
//@Handler("myhandler5")
public class MyHandler5 extends ChannelInitializer<SocketChannel> {
    private WebSocketClientHandshaker handshaker;

    @Autowired
    private ChannelFactory channelFactory;
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        NettyConfigProperties.Configuration configuration = channelFactory.getConfigs().get(MyHandler5.class);
        ch.pipeline().addLast(new HttpClientCodec());
        ch.pipeline().addLast(new HttpObjectAggregator(65535));
        handshaker = WebSocketClientHandshakerFactory.newHandshaker(configuration.getRemoteAddress(), WebSocketVersion.V13,null,true,new DefaultHttpHeaders());
        ch.pipeline().addLast(new WebSocketClientHandler(handshaker));
//        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
//            @Override
//            public void channelRead(ChannelHandlerContext ctx, Object msg)  throws Exception
//            {
//                //处理收到的数据，并反馈消息到到客户端
//                ByteBuf in = (ByteBuf) msg;
//                System.out.println("收到服务端发过来的消息: "+ in.toString(CharsetUtil.UTF_8));
//
//                //写入并发送信息到远端（客户端）
//                ctx.writeAndFlush(Unpooled.copiedBuffer("你好，我是客户端，我已经收到你发送的消息", Charset.forName("GBK")));
//            }
//
//            @Override
//            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
//            {
//                //出现异常的时候执行的动作（打印并关闭通道）
//                cause.printStackTrace();
//                ctx.close();
//            }
//        });
    }
}
